<template>
	<!-- 课程搜索 -->
	<view class="main">
		<v-search-nav 
		:subject_card_list='subject_card_list'
		:history_list='history_list'
		:is_history='isHistory'
		@confirmSearch='confirmSearch'
		@linkHistoryDetail='linkHistoryDetail'
		@clearHistory='clearHistory'
		@selectTime='selectTime'
		@ck='ck'
		@sureSubmit='sureSubmit'
		@clearLog='clearLog'
		></v-search-nav>
	</view>
</template>

<script>
	import searchbar from './components/search-teacher.vue'
	import utils from '@/common/util.js'
	export default {
		components: {
			vSearchNav: searchbar
		},
		data () {
			return {
				subject_card_list: [], // 搜索数据
				history_list: uni.getStorageSync('tearcherSearchCache') || [], // 历史记录列表
				isMore: false ,// 是否继续底部加载
				limit: 10, // 数据数量
				page: 1, // 页数 
				isHistory: true, // 是否显示历史记录
				search_name: '', // 搜索名称
				subjectList: uni.getStorageSync('zbSubject'), // 科目列表
				start_day: '', // 课程开始日期
				order: 0, // 排序,默认综合
			}
		},
		onReachBottom() {
			if (this.isHistory || this.subject_card_list.length <= 9) return 
			this.isMore = true
			uni.showLoading({title: '正在加载中...'})
			setTimeout(() => {
				this.getData('stu/course/infos/0', {
					search_name: this.search_name,
					limit: 10,
					page: ++this.page,
					kind_id: 0,
				}, 'getTeacherList')
			}, 500)
		},
		
		onLoad() {
			// 没有换成记录则加上一个记录key
			if (!uni.getStorageSync('tearcherSearchCache')) {
				uni.setStorage({
					key: 'tearcherSearchCache',
					data: []
				})
			}
		},
		methods: {
			/**
			 * @param {String} url 接口地址
			 * @param {Object} params 请求参数，以请求体的形式进行存放
			 * @param {Array} query 请求参数，以数组的形式进行存放，并进行拼接到url地址中如：baidu/xx1/xx2
			 * @param {mark} mark 请求标识，来操作不同的数据结果
			 */
			getData(url, params = {}, mark = '') {
				this.$zbapi.apiPost(url, params).then(res => {
					uni.hideLoading()
					if (res.data.code == 0) {
						switch(mark) {
							case 'getTeacherList':
								if (res.data.data.list.length <= 0) {
									if (!this.isMore) {
										this.subject_card_list = []
									}
									return this.showTotast('已无更多数据~')
								}
								// 对时间的处理
								res.data.data.list.forEach((item,index) => {
									item.start_month = utils.getAllTime(item.teach_start_day).substr(0, 4).replace(/-/g, '.')
									item.end_month = utils.getAllTime(item.teach_end_day).substr(0, 4).replace(/-/g, '.')
									item.subject_name = this.subjectList[item.subject_id]
									// 头像，最多取 4 个
									item.figureimgsList = !item.figureimgs ? [] : item.figureimgs.split(',').slice(0, 4)
									let now = parseInt(Date.now() / 1000)
									let enrol = parseInt((item.enrol_end_time - now) / 86400) // 获取截止日期
									if (enrol == 0 && (item.enrol_end_time - now) > 0) {
										item.enrol_end_time = 1
									} else {
										item.enrol_end_time = enrol
									}
								})
								// 判断是否需要累加，因为有可能是底部加载
								if (this.isMore) {
									this.subject_card_list = this.subject_card_list.concat(res.data.data.list)
								} else {
									this.subject_card_list = res.data.data.list
								}
							break;
						}
					} else {
						if (mark === 'getTeacherList') {
							if (!this.isMore) this.subject_card_list = []
							this.showTotast('搜索不到哦~')
						}
					}
				}).catch(err => {
					console.log(err);
					uni.hideLoading()
					this.showTotast('服务器出错啦~')
				})
			},
			
			// 开始搜索
			confirmSearch(search_name){
				if (this.search_name === search_name) return 
				this.search_name = search_name
				this.isHistory = false // 关闭历史
				this.isMore = false
				uni.showLoading({title: '搜索中...'})
				setTimeout(() => {
					this.getData('stu/course/infos/0', {
						search_name,
						limit: 10,
						kind_id: 0,
					}, 'getTeacherList')
				}, 500)
				// 每次搜索将搜索名称缓存到本地，以便拿到历史记录
				let _this = this
				uni.getStorage({ // 首先获取之前的缓存历史数据，在进行累加现在的历史新数据
					key: 'tearcherSearchCache',
					success: function(res) {
						let searchData = res.data
						for (let v of searchData) { // 确保新增的内容不会与原来的重复,如果重复则不会进行下一步的操作
							if (v === _this.search_name) return false
						}
						
						if (searchData.length > 10) searchData.pop()
						searchData.unshift(_this.search_name)
						// 开始设置
						uni.setStorage({
							key: 'tearcherSearchCache',
							data: searchData
						})
					}
				})
			},
			
			// 历史列表详情点击搜索
			linkHistoryDetail(histry_name) {
				this.isHistory = false // 关闭历史
				this.search_name = histry_name
				uni.showLoading({title: '搜索中...'})
				this.getData('stu/course/infos/0', {
					search_name: histry_name,
					limit: 10,
					kind_id: 0,
				}, 'getTeacherList')
			},
			
			// 清空历史记录
			clearHistory (){
				this.history_list = []
				uni.setStorage({
					key: 'tearcherSearchCache',
					data: []
				})
			},
			
			// 当搜索框没有值的时候将之前的列表清空
			clearLog() {
				this.subject_card_list = []
				this.isHistory = true // 挂起历史记录
				this.history_list = uni.getStorageSync('tearcherSearchCache') // 更新历史记录
				this.isMore = false
				this.page = 1
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				})
			},
			
			// 时间的筛选
			selectTime(item) {
				// 判断是否点击重置
				if (JSON.stringify(item) === '{}') {
					this.start_day = ''
					 this.getData('stu/course/infos/0', {
					 	search_name: this.search_name,
						order: this.order,
					 	limit: 10,
					 	kind_id: 0,
					 }, 'getTeacherList')
					 return
				}
				this.start_day = item.time 
			},
			
			// 确定选择时间
			sureSubmit() {
				this.getData('stu/course/infos/0', {
					search_name: this.search_name,
					date: this.start_day,
					order: this.order,
					limit: 10,
					kind_id: 0,
				}, 'getTeacherList')
			},
			
			// 排序
			ck(index) {
				this.order = index
				this.getData('stu/course/infos/0', {
					search_name: this.search_name,
					date: this.start_day,
					limit: 10,
					kind_id: 0,
					order: index
				}, 'getTeacherList')
			},
			
			// 封装吐司
			showTotast(title, icon = 'none') {
				uni.showToast({
					title: title,
					icon: icon
				})
			}
		}
	}
</script>

<style lang="scss">
	@import '../../static/font_lesson/iconfont.css';
	page {background: #FAFAFA;}
	.naver{padding-top: 148upx;}
	.banner{display:flex; justify-content: center; margin: 0 auto;}
	.type-wrap{padding:72upx 30upx;}
	
	.class-wrap{margin-top:12upx; padding:0 30upx;}
	.class-wrap .summary-wrap{display:flex; justify-content: space-between; flex-wrap:wrap;}
	.class-wrap .summary-wrap .item{ margin-top:30upx;}
	
	.title-wrap{display: flex;}
	.title-wrap .title{}
	.title-wrap .btn-more{flex:1; text-align: right;}
	
	.competitive-wrap{margin-top:12upx; padding:0 30upx;}
	.competitive-wrap .summary-wrap{display:flex; justify-content: space-between; flex-wrap:wrap;}
	.competitive-wrap .summary-wrap .item{margin-top: 36upx; width:100%;}
	
	.teacher-wrap{overflow: hidden; margin-top:12upx; padding:30upx 30upx;}
	.teacher-wrap .scroll-wrap{white-space:nowrap; width: 100%; margin-top:30upx;}
	.teacher-wrap .scroll-wrap .item{display:inline-block; margin-right:20upx;}
</style>
